/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aggregate.aggregator.remote;

import dao.CommentEntityFacadeLocal;
import dao.ContentEntityFacadeLocal;
import dao.ContentStatisticEntityFacadeLocal;
import dao.RateEntityFacadeLocal;
import entities.CommentEntity;
import entities.ContentEntity;
import entities.ContentStatisticEntity;
import entities.RateEntity;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import javax.naming.InitialContext;

/**
 *
 * @author vasi
 */
public class ClientRemoteImpl extends UnicastRemoteObject implements ClientRemoteInterface {

    private static ContentEntityFacadeLocal contentDAO;
    private static CommentEntityFacadeLocal commentDAO;
    private static ContentStatisticEntityFacadeLocal statisticDAO;
    private static RateEntityFacadeLocal rateDAO;

    private static ClientRemoteImpl remote = null;

    private static AggregatorRemoteInterface aggregator;

    static final String aggregatorHostname = "localhost";
    static final String clientHostname = "localhost";

    private ClientRemoteImpl() throws RemoteException{
        super();
    }

    public static ClientRemoteImpl getInstance(){
        if (remote == null){            
            try{
                /*if (System.getSecurityManager() == null) {
		    System.setSecurityManager (new RMISecurityManager());
		}*/
                remote = new ClientRemoteImpl();
                InitialContext ctx = new InitialContext();
                remote.contentDAO = (ContentEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/ContentEntityFacade");
                remote.statisticDAO = (ContentStatisticEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/ContentStatisticEntityFacade");
                remote.rateDAO = (RateEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/RateEntityFacade");
                remote.commentDAO = (CommentEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/CommentEntityFacade");
                Registry registry = LocateRegistry.getRegistry(aggregatorHostname, 5001);
		remote.aggregator = (AggregatorRemoteInterface)registry.lookup("Aggregator");
                System.out.println("Aggregator: "+remote.aggregator);
		/*ClientRemoteInterface clientStub = (ClientRemoteInterface)
				UnicastRemoteObject.exportObject(remote, 0);*/

		Registry client_registry = LocateRegistry.createRegistry(5002);
                //client_registry.unbind("ClientApplication");
		client_registry.rebind("ClientApplication", remote);
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        return remote;
    }

    public static void testNotify(ContentItem item) throws Exception{
        InitialContext ctx = new InitialContext();
        contentDAO = (ContentEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/ContentEntityFacade");
        statisticDAO = (ContentStatisticEntityFacadeLocal)ctx.lookup("java:global/AggregatorClient-war/ContentStatisticEntityFacade");

        ContentEntity entity = new ContentEntity();
        entity.setTitle(item.getTitle());
        entity.setBody(item.getBody());
        entity.setCreated(System.currentTimeMillis()/1000);
        entity.setStatus(new Integer(1));
        entity.setCid(new Long(item.getId()));
        contentDAO.create(entity);

        //create a new entry in statistics.
        ContentStatisticEntity stats = new ContentStatisticEntity();
        stats.setCid(entity.getCid());
        stats.setComment_number(new Long(0));
        stats.setRating(new Double(0.0));
        stats.setViews(new Long(0));
        statisticDAO.create(stats);
    }

    public void notify(ContentItem item) throws RemoteException{
        ContentEntity entity = new ContentEntity();
        entity.setTitle(item.getTitle());
        entity.setBody(item.getBody());
        entity.setCreated(System.currentTimeMillis()/1000);
        entity.setStatus(new Integer(1));
        entity.setCid(new Long(item.getId()));
        contentDAO.create(entity);
        
        //create a new entry in statistics.
        ContentStatisticEntity stats = new ContentStatisticEntity();
        stats.setCid(entity.getCid());
        stats.setComment_number(new Long(0));
        stats.setRating(new Double(0.0));
        stats.setViews(new Long(0));
        statisticDAO.create(stats);
    }

    public void notifyRating(int contentId, double value) throws RemoteException{
        ContentStatisticEntity stats = statisticDAO.findByContentId(new Long(contentId));
        if (stats != null){
            //Create a new rate entry
            RateEntity rate = new RateEntity();
            rate.setCid(new Long(contentId));
            rate.setCreated(System.currentTimeMillis()/1000);
            rate.setRate_value(value);
            rate.setUid(new Long(0));
            rateDAO.create(rate);
            //Update the statistics.
            double rate_avg = rateDAO.calculateAvgRate(new Long(contentId));
            stats.setRating(rate_avg);
            statisticDAO.edit(stats);
        }
        
    }
    public void notifyComment(Comment comment) throws RemoteException{
        ContentStatisticEntity stats = statisticDAO.findByContentId(new Long(comment.getContentId()));
        if (stats != null){
            //Create the new comment.
            CommentEntity comment_entity = new CommentEntity();
            comment_entity.setAuthor(comment.getAuthor());
            comment_entity.setChanged(System.currentTimeMillis()/1000);
            comment_entity.setComment(comment.getBody());
            comment_entity.setCon_id(new Long(comment.getContentId()));
            comment_entity.setCreatd(System.currentTimeMillis()/1000);
            comment_entity.setParent_id(new Long(0));
            comment_entity.setSubject(comment.getSubject());
            comment_entity.setUid(new Long(0));
            commentDAO.create(comment_entity);
            //Update the statistics.
            stats.setComment_number(stats.getComment_number()+1);
            statisticDAO.edit(stats);
        }
    }

    public void ratingAdded(int contentId, double value){
        try {
            remote.aggregator.addRating(contentId, value);
        } catch (RemoteException e){
            e.printStackTrace();
        }
    }

    public void commentAdded(int contentId, Comment comment){
        try{
            remote.aggregator.addComment(contentId, comment);
        } catch(RemoteException e){
            e.printStackTrace();
        }
    }

    public void subscribe(String hostname, int categoryId){
        try {
            remote.aggregator.subscribe(hostname, categoryId);
        } catch (RemoteException e){
            e.printStackTrace();
        }
    }
}
